<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { getForumArticleListService } from '@/api/forumArticle'
import { useRouter, useRoute } from 'vue-router'

import { useForumBoardStore } from '@/store/forumBoard';

// 板块状态
const forumBoardStore = useForumBoardStore();

const router = useRouter()
const route = useRoute()

// 搜索条件切换
const handleTabChange = async (tab) => {
  // 最新/最热
  forumArticleSearchCondition.value.orderType = tab.props.name

  // 搜索条件一切换，从第一页重新获取
  forumArticleSearchCondition.value.pageNum = 1

  // 清空当前页面中的文章
  forumArticleList.value = []

  // 重新开始加载
  pageFinished.value = false
  pageLoading.value = false

  let res = await getForumArticleListService(forumArticleSearchCondition.value)

  forumArticleList.value = res.data.forumArticleList
  // forumArticleList.value.push(...res.data.forumArticleList)
  forumArticleListTotal.value = res.data.total
}

// 文章列表搜索条件
const forumArticleSearchCondition = ref({
  pageNum: 1, // 页数
  pageSize: 10, // 每页条数
  boardId: null, // 一级板块
  parentBoardId: null, // 二级板块
  boardName: null, // 一级板块
  parentBoardName: null, // 二级板块
  orderType: 0, // 排序方式
})
const forumArticleList = ref([])
const forumArticleListTotal = ref(0)

// 获取文章列表
const getForumArticleList = async () => {
  // 如果已经在加载了，就不执行文章搜索，防止等待加载期间多次搜索
  if (pageLoading.value || pageFinished.value) return

  // 开始搜索，显示加载框
  pageLoading.value = true
  pageError.value = null

  try {
    let res = await getForumArticleListService(forumArticleSearchCondition.value)
    console.log("获取到的文章如下", res.data)
    // forumArticleList.value = result.data.forumArticleList
    forumArticleList.value.push(...res.data.forumArticleList)
    forumArticleListTotal.value = res.data.total

    // 页数+1
    forumArticleSearchCondition.value.pageNum++

    // 判断是否还有更多数据
    if (res.data.forumArticleList.length < forumArticleSearchCondition.value.pageSize) { // 没有更多数据了
      pageFinished.value = true
    }

  } catch (err) {
    pageError.value = err.message || '请求失败'
    console.error('请求错误:', err)
  } finally {
    pageLoading.value = false
  }

}

// 跳转到用户中心页
const goToUserCenter = (userId) => {
  router.push(`/userCenter/${userId}`)
}

// 跳转到文章详情页
const goToArticleDetail = (articleId) => {
  router.push(`/article/detail/${articleId}`)
}

// onMounted(() => {
//   // 获取文章列表
//   getForumArticleList()
// })

// 滚动处理
const pageLoading = ref(false)
const pageFinished = ref(false)
const pageError = ref(null)
const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight

  // 距离底部50px时加载
  if (scrollTop + windowHeight >= scrollHeight - 50 && !pageLoading.value && !pageFinished.value) {
    console.log("要翻页喽")
    getForumArticleList()
  }
}

// 添加滚动监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

// 移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})


watch(
  () => route.params,
  (newValue, oldValue) => {
    console.log("content页面的路由参数：", newValue)
    if (newValue == undefined || newValue == null) {
      console.log("当前无路由")
      return
    }

    // 文章列表置空
    forumArticleList.value = []
    forumArticleListTotal.value = 0
    forumArticleSearchCondition.value.pageNum = 1
    forumArticleSearchCondition.value.orderType = 0

    // 搜索条件中的板块信息置空
    forumArticleSearchCondition.value.parentBoardName = null
    forumArticleSearchCondition.value.boardName = null

    // 解析路径中的板块信息
    if (newValue.boardName2 == null) {
      // 只有一级板块
      forumArticleSearchCondition.value.parentBoardName = newValue.boardName1
    } else {
      // 一级板块 和 二级板块
      forumArticleSearchCondition.value.boardName = newValue.boardName2
      forumArticleSearchCondition.value.parentBoardName = newValue.boardName1
    }

    // 继续开始加载
    pageFinished.value = false
    pageLoading.value = false

    // 获取文章列表
    getForumArticleList()
  },
  { immediate: true, deep: true }
)

</script>

<template>
  <div class="home-container">
    <!-- 头部搜索条件 -->
    <div class="list-header">
      <el-tabs v-model="forumArticleSearchCondition.orderType" class="demo-tabs" @tab-click="handleTabChange">
        <el-tab-pane label="推荐" :name="0"></el-tab-pane>
        <el-tab-pane label="最新" :name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <!--骨架过渡效果  -->
    <!-- <div class="skeleton" v-if="forumArticleList.length == 0 && loading == true">
      <el-skeleton :row="2" animated></el-skeleton>
    </div>
    <div v-if="forumArticleList.length == 0 && loading == false" class="empty-res">
      <el-empty description="暂无数据" />
    </div> -->
    <!-- 文章列表 -->
    <div class="list">
      <ul>
        <li class="list-item" v-for="item in forumArticleList">
          <!-- 文章item -->
          <div class="item-content" @click="goToArticleDetail(item.articleId)">
            <div class="item-title">{{ item.title }}</div>
            <div class="item-intro">{{ item.summary == null ? "暂无简介" : item.summary }}</div>
            <div class="item-footer">
              <div class="item-footer-l">
                <span class="footer-item item-author" @click.stop=goToUserCenter(item.userId)>{{
                  item.nickname
                }}</span>
                <span class="footer-item iconfont icon-eye"></span>
                <span class="footer-item">{{ item.commentCount == 0 ? "阅读" : item.commentCount }}</span>
                <span class="footer-item iconfont icon-appreciate"></span>
                <span class="footer-item">{{ item.likeCount == 0 ? "点赞" : item.likeCount }}</span>
              </div>
              <div class="item-footer-r">
                <span class="board-name" v-if="item.boardName"
                  @click.stop="router.push(`/${item.parentBoardName}/${item.boardName}`)">{{
                    item.boardName }}</span>
                <span class="board-name" v-if="item.parentBoardName"
                  @click.stop="router.push(`/${item.parentBoardName}`)">{{
                    item.parentBoardName }}</span>
              </div>
            </div>
          </div>
          <!-- <img src="https://tse2-mm.cn.bing.net/th/id/OIP-C.LI7eFHOuMtjMsGK2JWeCsQHaHa?rs=1&pid=ImgDetMain"
            class="item-cover"></img> -->
          <img v-if="item.cover != null && item.cover != ''" :src="item.cover" class="item-cover"></img>
        </li>
      </ul>
    </div>
    <!-- 翻页时出现 -->
    <!-- 加载状态 -->
    <div v-if="pageLoading" class="pageLoading">加载中...</div>
    <!-- 没有更多数据 -->
    <div v-if="pageFinished" class="no-more">没有更多数据了</div>
    <!-- 错误提示 -->
    <div v-if="pageError" class="error">{{ pageError }}</div>
  </div>
</template>

<style scoped>
/* 翻页相关 */
.pageLoading,
.no-more,
.error {
  padding: 15px;
  text-align: center;
  color: #999;
  background-color: #f2f3f5;
}

.error {
  color: #f56c6c;
}

/* 中间文章列表 */
.home-container {
  width: 730px;
  height: 100%;
  background-color: #fff;
}

/* 头部搜索条件 */
.home-container .list-header {
  border-bottom: 1px solid #e4e6eb;
  padding: 5px 20px 0px;
  font-size: 15px;
}

/* 骨架过渡效果 */
.home-container .skeleton {
  padding: 10px;
}

/* 文章列表 */
.list .list-item {
  width: 100%;
  height: 100px;
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid rgba(228, 230, 235, 0.5);
  cursor: pointer;
}

.list .list-item:hover {
  background-color: #f7f8fa;
}

.list .list-item .item-content {
  flex: 1;
  margin-right: 10px;
  width: 80%;
}

/* 文章标题 */
.home-container .list .list-item .item-title {
  font-weight: 600;
  font-size: 16px;
  line-height: 24px;
  color: #252933;
  /* 强制文本在同一行显示 */
  white-space: nowrap;
  /* 隐藏超出容器范围的文本 */
  overflow: hidden;
  /* 显示省略号 */
  text-overflow: ellipsis;
}

/* 文章内容 */
.home-container .list .list-item .item-intro {
  color: #8a919f;
  font-size: 13px;
  line-height: 32px;
  /* 强制文本在同一行显示 */
  white-space: nowrap;
  /* 隐藏超出容器范围的文本 */
  overflow: hidden;
  /* 显示省略号 */
  text-overflow: ellipsis;
}

/* 文章底部 */
.home-container .list .list-item .item-footer {
  font-size: 13px;
  line-height: 22px;
  color: #8a919f;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.home-container .list .list-item .item-footer .item-footer-l {
  display: flex;
  align-items: center;
}

.home-container .list .list-item .item-footer .iconfont {
  font-size: 15px;
}

.home-container .list .list-item .item-footer .footer-item {
  padding-right: 20px;
}

.home-container .list .list-item .item-footer .footer-item:nth-child(2n) {
  padding-right: 5px;
  display: block;
  margin-top: 1px;
}

.home-container .list .list-item .item-footer .item-author {
  max-width: 132px;
  /* 强制文本在同一行显示 */
  white-space: nowrap;
  /* 隐藏超出容器范围的文本 */
  overflow: hidden;
  /* 显示省略号 */
  text-overflow: ellipsis;
}

.home-container .list .list-item .item-footer .item-author:hover {
  color: #67C23A;
}

.home-container .list .list-item .item-footer .item-footer-r .board-name {
  background-color: #f2f3f5;
  padding: 0 6px;
  border-radius: 2px;
  margin-left: 6px;
  color: #8a919f;
  cursor: pointer;
  font-size: 13px;
  line-height: 18px;
}

.home-container .list .list-item .item-footer .item-footer-r .board-name:hover {
  color: green;
}

/* 文章封面 */
.home-container .list .list-item .item-cover {
  width: 110px;
  /* 使用cover不会出现留空白 */
  object-fit: cover;
  /* background-color: blue; */
  border-radius: 4px;
}
</style>